package com.gzwh.v1.sysapi.server.member.impl;

import com.gzwh.v1.sysapi.dao.application.SysAppRegMapper;
import com.gzwh.v1.sysapi.entity.application.SysAppReg;
import com.gzwh.v1.sysapi.entity.application.SystemApplication;
import com.gzwh.v1.sysapi.entity.application.UserApplication;
import com.gzwh.v1.sysapi.server.member.ApplicationRegServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * 负责应用创建以及管理
 * 时间：2019-08-24
 * 作者：蛋炒饭
 */
@Service
public class ApplicationRegServerImpl implements ApplicationRegServer {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    SysAppRegMapper sysAppRegMapper;


    //该用户id下能否再创建该应用，返回false，则该用户不能创建，返回true，表示该用户可以创建应用
    public boolean allowCheckUserCreateByUid(Long uid, Long aid) {
        boolean status = false;
        int count = sysAppRegMapper.getUidAndAidToCount(aid, uid); //获取该用户id下的应用数

        UserApplication userApplication = sysAppRegMapper.findUserAppByuid(uid);   //该用户下能创建多少应用数

        SystemApplication systemApplication = sysAppRegMapper.findUserApplicationByid(aid);//应用id的详细信息
        try {
            if (systemApplication.getInside().equals("weixin")) {
                if (userApplication.getWeixin() <= count) {
                    throw new Exception("当前用户创建微信，但数量大于可创建数量");
                }
                status = true;
            }
            if (systemApplication.getInside().equals("dinner")){
                if (userApplication.getDinner()<=count){
                    throw  new Exception("数量超过限制");
                }
                status=true;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            status = false;
        }
        return status;
    }

    public int insertAppReg(Long uid,Long aid){
        SystemApplication systemApplication = sysAppRegMapper.findUserApplicationByid(aid);//应用id的详细信息
        SysAppReg sysAppReg=new SysAppReg();
        sysAppReg.setAid(aid);
        sysAppReg.setUid(uid);
        sysAppReg.setUuid(UUID.randomUUID().toString());
        sysAppReg.setPublicKey(UUID.randomUUID().toString());
        sysAppReg.setPrivateKey(UUID.randomUUID().toString());
        int count=sysAppRegMapper.insetTo(sysAppReg);
        return count;
    }
}
